package com.yin.myproject.netty.chapter10.demo01;

import com.yin.myproject.netty.HttpConstants;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.stream.ChunkedWriteHandler;

/**
 * Http文件服务器
 *
 * @author Eason
 * @create 2018-01-01 13:54
 **/
public class HttpFileServer {
    private static final String DEFAULT_URL = "/";
    private String host;
    private String port;

    public void run(final int port, final String host, final String url) {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(HttpConstants.HTTP_DECODER, new HttpRequestDecoder());
                            socketChannel.pipeline().addLast(HttpConstants.HTTP_AGGREGATOR, new HttpObjectAggregator(65536));
                            socketChannel.pipeline().addLast(HttpConstants.HTTP_ENCODER, new HttpResponseEncoder());
                            socketChannel.pipeline().addLast(HttpConstants.HTTP_CHUNKED, new ChunkedWriteHandler());
                            socketChannel.pipeline().addLast("fileServerHandler", new HttpFileServerHandler(url));
                        }
                    });
            ChannelFuture future = serverBootstrap.bind(host, port).sync();
            System.out.println("Http 文件目录服务器启动,网址是 : http://" + host + ":" + port + url);
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        new HttpFileServer().run(8080, "127.0.0.1", DEFAULT_URL);
    }
}
